import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from "@/router/index";
import layoutStore from "@store/layoutStore.ts";
import {refreshRouter} from "@router/dynamicRouter.ts";

NProgress.configure({showSpinner: false});

router.beforeEach(async (to, from, next) => {
    NProgress.start()

    /**
     * 修改标题
     */
    setTitle(to, from, next);

    /**
     * 页面刷新
     */
    let isSuccess = await onF5(to, from, next)
    if (!isSuccess) return;


    // 处理路由参数
    await routerMetaHandler(to, from, next)

    // 放行
    console.log("路由-全局拦截-放行", to, from, next)
    next();
})

function setTitle(to: any, from: any, next: any) {
    let {title} = to.meta;
    console.log("title", title);
    // 更新窗口Title
    document.title = title;
}

router.afterEach(() => {
    NProgress.done()
})

async function routerMetaHandler(to: any, from: any, next: any) {
    console.log("路由参数处理--to", to)
    console.log("路由参数处理--from", from)
    console.log("路由参数处理--next", next)
}

async function onF5(to: any, from: any, next: any) {
    // 没刷新，直接放行
    if (!layoutStore().isRefresh) return true;
    layoutStore().isRefresh = false

    //刷新路由
    await refreshRouter()

    console.log("路由-onF5刷新-重新执行", to, from, next)
    next({...to, replace: true})
    return false;
}
